package com.example.socketdemo.socket;

import com.google.common.collect.Maps;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.http.ServerWebSocket;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
public class VertxSocketServer extends AbstractVerticle {


    private final static Map<String, ServerWebSocket> LOCAL_MAP = Maps.newHashMap();

    @Override
    public void start() throws Exception {
        vertx.createHttpServer().webSocketHandler(serverWebSocket -> {
            String path = serverWebSocket.path();
            String id = serverWebSocket.textHandlerID();
            if (path.equals("/myapp")) {
                serverWebSocket.handler(buffer -> {
                    LOCAL_MAP.put(id, serverWebSocket);
                    System.out.println("--------------------");
                    System.out.println("server收到消息: " + buffer.toString());
                    System.out.println("--------------------");
                    serverWebSocket.writeTextMessage("我是服务器，我收到你的消息了 " + LocalDateTime.now());
                });
            } else {
                serverWebSocket.reject(); // 拒绝连接
            }

            serverWebSocket.closeHandler(res -> {
                log.info("socket 断开连接==== {}", id);
                LOCAL_MAP.remove(id);
            });


        }).listen(9099, server -> {
            if (server.succeeded()) {
                System.out.println("启动成功");
            } else {
                server.cause().printStackTrace();
            }
        });


        // 模拟全局推送消息 30秒后
        vertx.setPeriodic(10000, timer -> {
            System.out.println("时间到了， map size " + LOCAL_MAP.size());
            LOCAL_MAP.forEach((k, v) -> {
                System.out.println("定时任务触发");
                System.out.println("id: " + k);
                v.writeTextMessage("我是服务器，这是定时任务发送的消息 " + LocalDateTime.now());
//                v.close(); // 自己决定什么时候关闭
            });
        });

    }


    public static void send(String message) {
        LOCAL_MAP.forEach((k, v) -> {
            System.out.println("定时任务触发");
            System.out.println("id: " + k);
            v.writeTextMessage(message + LocalDateTime.now());
//            v.close(); // 自己决定什么时候关闭
        });
    }




    public static void main(String[] args) {
        Vertx.vertx().deployVerticle(new VertxSocketServer());
    }


}

